<template>
  <t-card :bordered="false">
    <div class="container">
      <!-- 消息组树 -->
      <message-group-tree ref="messageGroupTreeRef" v-model:selected-id="selectedId" class="left" />
      <div class="right">
        <!-- 自定义搜索 -->
        <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleSeachTable">
          <t-col :span="4">
            <t-form-item label="模板编号" name="modelCode">
              <t-input v-model:value="params.modelCode" clearable placeholder="" />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="模板名称" name="modelName">
              <t-input v-model:value="params.modelName" clearable placeholder="" />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="发送类型" name="sendType">
              <t-select
                v-model:value="params.sendType"
                :options="dictionaryStore.get('send_type')"
                clearable
                filterable
                placeholder=""
              />
            </t-form-item>
          </t-col>
          <!-- <t-col :span="4">
            <t-form-item label="接收人类型" name="recipientType">
              <t-select
                v-model:value="params.recipientType"
                :options="dictionaryStore.get('recipient_type')"
                clearable
                filterable
                placeholder=""
              />
            </t-form-item>
          </t-col> -->
          <t-col :span="4">
            <t-form-item label="消息类型" name="messageType">
              <t-select
                v-model:value="params.messageType"
                :options="dictionaryStore.get('message_type')"
                clearable
                filterable
                placeholder=""
              />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="消息内容" name="message">
              <t-input v-model:value="params.message" clearable placeholder="" />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="是否超时发送" name="isTimeoutSend">
              <t-select
                v-model:value="params.isTimeoutSend"
                :options="dictionaryStore.get('is_type')"
                clearable
                filterable
                placeholder=""
              />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="操作类型" name="operateType">
              <t-select
                v-model:value="params.operateType"
                :options="dictionaryStore.get('decoration_order_operate_type')"
                clearable
                filterable
                placeholder=""
              />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="创建时间" name="createTime">
              <t-date-range-picker
                allow-input
                v-model:value="params.createTime"
                clearable
                enable-time-picker
                placeholder=" "
                style="width: 100%"
              />
            </t-form-item>
          </t-col>
        </custom-search>
        <!-- 自定义表格 -->
        <custom-table
          ref="customTableRef"
          row-key="id"
          :columns="columns"
          :api="messageTemplateCRUD.page"
          column-controller-key="messageTemplateList"
        >
          <template #topContent>
            <div style="margin-bottom: var(--td-comp-margin-xxl)">
              <t-button
                v-permission="['system:message-model-config:create']"
                @click="
                  handleOpenDialog('create', {
                    // parentId: selectedId
                    parentId: [],
                    recipientType: [],
                  })
                "
              >
                新建模板
              </t-button>
            </div>
          </template>
          <template #parentId="{ row }">
            {{ analysisParentId(row.parentId) }}
          </template>
          <template #sendType="{ row }">
            {{ dictionaryStore.analysis('send_type', row.sendType) }}
          </template>
          <template #recipientType="{ row }">
            {{ analysisRecipientType(row.recipientType, row.sendType) }}
          </template>
          <template #messageType="{ row }">
            {{ dictionaryStore.analysis('message_type', row.messageType) }}
          </template>
          <template #isTimeoutSend="{ row }">
            {{ dictionaryStore.analysis('is_type', row.isTimeoutSend) }}
          </template>
          <template #operateType="{ row }">
            {{ dictionaryStore.analysis('decoration_order_operate_type', row.operateType) }}
          </template>
          <template #createTime="{ row }">
            {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template #operation="{ row }">
            <t-space>
              <t-link
                v-permission="['system:message-model-config:query']"
                theme="primary"
                @click="handleOpenDialog('read', { id: row.id })"
              >
                详情
              </t-link>
              <t-link
                v-permission="['system:message-model-config:update']"
                theme="primary"
                @click="handleOpenDialog('update', { id: row.id })"
              >
                编辑
              </t-link>
              <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
                <t-link v-permission="['system:message-model-config:delete']" theme="danger"> 删除 </t-link>
              </t-popconfirm>
            </t-space>
          </template>
        </custom-table>
      </div>
      <!-- <t-empty v-show="!selectedId" class="right" title="请先选择部门" style="margin-top: 250px" /> -->
    </div>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly, mode }"
      :api-map="messageTemplateCRUD"
      header="*模板"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item label="消息组" name="parentId" :rules="[{ required: true, message: '请选择消息组' }]">
        <t-cascader
          v-model:value="formData.parentId"
          :options="messageGroupTreeRef?.messageGroupTree"
          :keys="{ value: 'id', label: 'name' }"
          placeholder="请选择消息组"
          filterable
          clearable
          check-strictly
          multiple
        />
      </t-form-item>
      <t-form-item label="模板编号" name="modelCode" :rules="[{ required: true, message: '请输入模板编号' }]">
        <t-input
          v-model:value="formData.modelCode"
          placeholder="请输入模板编号"
          clearable
          :readonly="mode !== 'create'"
        />
      </t-form-item>
      <t-form-item label="模板名称" name="modelName" :rules="[{ required: true, message: '请输入模板名称' }]">
        <t-input v-model:value="formData.modelName" placeholder="请输入模板名称" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="发送类型" name="sendType" :rules="[{ required: true, message: '请选择发送类型' }]">
        <t-select
          v-model:value="formData.sendType"
          :options="dictionaryStore.get('send_type')"
          placeholder="请选择发送类型"
          clearable
          filterable
          :readonly="readonly"
          @change="formData.recipientType = []"
          @clear="formData.sendType = null"
        />
      </t-form-item>
      <t-form-item label="接收人类型" name="recipientType" :rules="[{ required: true, message: '请选择接收人类型' }]">
        <t-select
          v-model:value="formData.recipientType"
          :options="recipientTypeOptions(formData.sendType)"
          placeholder="请选择接收人类型"
          clearable
          filterable
          :readonly="readonly"
          multiple
          @clear="formData.recipientType = []"
        />
      </t-form-item>
      <t-form-item label="消息类型" name="messageType" :rules="[{ required: true, message: '请选择消息类型' }]">
        <t-select
          v-model:value="formData.messageType"
          :options="dictionaryStore.get('message_type')"
          placeholder="请选择消息类型"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.messageType = null"
        />
      </t-form-item>
      <t-form-item label="消息内容" name="message" :rules="[{ required: true, message: '请输入消息内容' }]">
        <t-textarea v-model:value="formData.message" placeholder="请输入消息内容" :readonly="readonly" />
      </t-form-item>
      <t-form-item
        label="是否超时发送"
        name="isTimeoutSend"
        :rules="[{ required: true, message: '请选择是否超时发送' }]"
      >
        <t-select
          v-model:value="formData.isTimeoutSend"
          :options="dictionaryStore.get('is_type')"
          placeholder="请选择是否超时发送"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.isTimeoutSend = null"
        />
      </t-form-item>
      <t-form-item label="超时时间" name="timeout" :rules="[{ required: true, message: '请输入超时时间' }]">
        <t-input-number
          v-model:value="formData.timeout"
          :decimal-places="0"
          min="0"
          :allow-input-over-limit="false"
          placeholder="请输入超时时间"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="操作类型" name="operateType" :rules="[{ required: true, message: '请选择操作类型' }]">
        <t-select
          v-model:value="formData.operateType"
          :options="dictionaryStore.get('decoration_order_operate_type')"
          placeholder="请选择操作类型"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.operateType = null"
        />
      </t-form-item>
      <t-form-item label="显示顺序" name="sort" :rules="[{ required: true, message: '请输入显示顺序' }]">
        <t-input-number
          v-model:value="formData.sort"
          :decimal-places="2"
          min="0"
          :allow-input-over-limit="false"
          placeholder="请输入显示顺序"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'MessageTemplate',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, ref, useTemplateRef, watch } from 'vue';

import { messageTemplateCRUD } from '@/api/config/message-template';
import { getSimpleRoleList } from '@/api/system/role';
import { getSimpleUserList } from '@/api/system/user';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import MessageGroupTree from '@/pages/config/message-group/components/MessageGroupTree.vue';
import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 精简角色列表
const simpleRoleList = ref([]);
// 处理获取精简角色列表
const handleGetSimpleRoleList = () => {
  getSimpleRoleList().then((data) => {
    simpleRoleList.value = data;
  });
};
handleGetSimpleRoleList();
// 精简用户列表
const simpleUserList = ref([]);
// 处理获取精简用户列表
const handleGetSimpleUserList = () => {
  getSimpleUserList().then((data) => {
    simpleUserList.value = data;
  });
};
handleGetSimpleUserList();
// 消息组树ref
const messageGroupTreeRef = useTemplateRef('messageGroupTreeRef');
// 选择的id
const selectedId = ref();
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'sort', title: '显示顺序' },
  { colKey: 'id', title: '模板ID' },
  { colKey: 'parentId', title: '消息组' },
  { colKey: 'modelCode', title: '模板编号' },
  { colKey: 'modelName', title: '模板名称' },
  { colKey: 'sendType', title: '发送类型' },
  { colKey: 'recipientType', title: '接收人类型' },
  { colKey: 'messageType', title: '消息类型 ' },
  { colKey: 'message', title: '消息内容' },
  { colKey: 'isTimeoutSend', title: '是否超时发送' },
  { colKey: 'timeout', title: '超时时间' },
  { colKey: 'operateType', title: '操作类型' },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 150, fixed: 'right' },
];
const handleSeachTable=(params:any) =>{
  if(params=='reset') handleInitTable()
  if(params!='reset') handleInitTable(selectedId.value)
  
}

// 处理初始化表格
const handleInitTable = (parentId:any=null) => {
  const params = {
    ...customSearchRef.value.params,
  };
  // 只有当明确传递了 parentId 时才设置它
  if (parentId !== null) {
    params.parentId = parentId;
  } else {
    // 如果没有传递 parentId，确保 params 中没有 parentId
    delete params.parentId;
    selectedId.value = null;
  }
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
watch(
  () => selectedId.value,
  (newValue) => {
    handleInitTable(newValue)
  },
);
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  messageTemplateCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 接收人类型选项
const recipientTypeOptions = (sendType: string) => {
  if (sendType === '1') {
    return simpleRoleList.value.map((item) => {
      return { ...item, value: item.id, label: item.name };
    });
  }
  if (sendType === '2') {
    return dictionaryStore.get('send_message_script', 'number');
  }
  if (sendType === '3') {
    return simpleUserList.value.map((item) => {
      return { ...item, value: item.id, label: item.nickname };
    });
  }
  return [];
};
// 解析父级id
const analysisParentId = (parentId: number[]) => {
  let result = '';
  const messageGroupList = messageGroupTreeRef.value?.messageGroupList;
  if(parentId) {
      parentId.forEach((id, index) => {
        const obj = messageGroupList.find((item) => item.id === id);
        if (index > 0 && obj) result += ' / ';
        if (obj) result += obj.name;
      });
  }
  return result;
};
// 解析接收人类型
const analysisRecipientType = (recipientType: number[], sendType: string) => {
  let result = '';
  const options = recipientTypeOptions(sendType);
  recipientType.forEach((id, index) => {
    const obj = options.find((item) => item.value === id);
    if (index > 0 && obj) result += ' / ';
    if (obj) result += obj.label;
  });
  return result;
};
</script>

<style lang="less" scoped>
.container {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  @leftWidth: 300px;

  .left {
    width: @leftWidth;
  }

  .right {
    width: calc(100% - @leftWidth);
  }
}
</style>
